package com.hsmpay.mobile.action.account.qian48;

import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.DateConvertUtil;
import com.hsmpay.common.util.URLDecoderTools;
import com.hsmpay.mobile.pojo.trans.TransOrder;
import com.hsmpay.mobile.pojo.trans.TransPriorSettle;
import com.hsmpay.mobile.service.trans.TransPriorSettleService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.hsmpay.utils.TimeUtils;

import javax.annotation.Resource;
import java.net.ConnectException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 千48撤销 action
 *
 * @author 颜铃璋
 * @date 2013-8-27
 */
@Controller("q4RevocationAction")
@Scope("prototype")
public class Q4RevocationAction extends Q4BaseAction {
    private static final long serialVersionUID = -6685556721396542845L;
    private static Logger log = Logger.getLogger(Q4RevocationAction.class);
    /*protected TransOrderService<TransOrder,Long> transOrderService;*/
    @Resource(name = "transPriorSettleService")
    private TransPriorSettleService<TransPriorSettle, Long> transPriorSettleService;

    /**
     * localhost/wanjxMobile/qian48/revocation_revocation.action?userId=623&orgMerchantOrderId=201309220930380307&terminalId=1050000000009a27730a&merchantOrderId=201309221250210946&merchantOrderTime=20130922125021&transAmt=5666
     * 撤销我要收款
     *
     * @return
     * @throws Exception
     */
    public String revocation() throws Exception {
        log.debug("--- revocation() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        roleId = Long.parseLong(js.getString("roleId"));
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        if (js.containsKey("orgMerchantOrderId"))
            orgMerchantOrderId = js.getString("orgMerchantOrderId");
        if (js.containsKey("merchantOrderId"))
            merchantOrderId = js.getString("merchantOrderId");
        if (js.containsKey("merchantOrderTime"))
            merchantOrderTime = js.getString("merchantOrderTime");
        if (js.containsKey("terminalId"))
            terminalId = js.getString("terminalId");
        if (js.containsKey("transAmt"))
            transAmt = js.getString("transAmt");
        if (js.containsKey("merchantSign"))
            merchantSign = js.getString("merchantSign");
        if (js.containsKey("senderSign"))
            senderSign = js.getString("senderSign");
        if (js.containsKey("serviceInfo"))
            serviceInfo = js.getString("serviceInfo");
        if (js.containsKey("terminalInfo"))
            terminalInfo = js.getString("terminalInfo");
        if (js.containsKey("mac"))
            mac = js.getString("mac");

        log.debug("userId = " + userId);//用户ID
        log.debug("clientType = " + clientType);//
        log.debug("terminalTypeId = " + terminalTypeId);//

        log.debug("orgMerchantOrderId = " + orgMerchantOrderId);//商户订单
        log.debug("merchantOrderId = " + merchantOrderId);//商户订单
        log.debug("merchantOrderTime = " + merchantOrderTime);//商户订单时间
//		log.debug("terminalId = " + terminalId);//终端代码
        log.debug("transAmt = " + transAmt);//终端代码
        //log.debug("transId = " + transId);//交易流水号
        //log.debug("dynamicKeyData = " + dynamicKeyData);//交易金额
        log.debug("merchantSign" + merchantSign);//商户数字签名
        log.debug("senderSign" + senderSign);//发送方数字签名
        log.debug("serviceInfo" + serviceInfo);//服务信息
        log.debug("terminalInfo" + terminalInfo);//终端信息 手机串号、号码、os、序列号等
        //log.debug("mac" + mac);

        if (null == userId) {
            log.warn("撤销我要收款时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (StringUtils.isBlank(merchantOrderId)) {
            log.warn("撤销我要收款时, 传入参数merchantOrderId为空");
            sendAppErrorMsg("6001", "merchantOrderId");
            return null;
        }
        if (StringUtils.isBlank(merchantOrderTime)) {
            log.warn("撤销我要收款时, 传入参数merchantOrderTime为空");
            sendAppErrorMsg("6001", "merchantOrderTime");
            return null;
        }

        if (StringUtils.isBlank(orgMerchantOrderId)) {
            log.warn("撤销我要收款时, 传入参数orgMerchantOrderId为空");
            sendAppErrorMsg("6001", "orgMerchantOrderId");
            return null;
        }

//        if (!roleId.equals(2l) && !roleId.equals(3l)) {//加密型
//            if (StringUtils.isBlank(terminalId)) {
//                log.warn("撤销我要收款时, 传入参数terminalId为空");
//                sendAppErrorMsg("6001", "terminalId");
//                return null;
//            }
//        }

        if (false) {//暂时暂停  撤销接口
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("reqCode", "0000");
            result.put("reqMsg", "网络超时,正在努力连接银联交易系统,请稍候查询交易列表！");
            sendAppMsg(result);
            return null;
        }
        Qian4SendLog send = null;
        try {
            User user = userService.getUserById(userId);
            if (null != user) {
                //判断日期是否是今天
                Date date = new Date();
                String today = DateConvertUtil.dateString(date, "yyyyMMdd");//
                if (!merchantOrderTime.startsWith(today)) {
                    merchantOrderId = getMerchantOrderId(date, user.getLoginName());
                    merchantOrderTime = DateConvertUtil.dateString(date, "yyyyMMddHHmmss");
                }

                TransPriorSettle transPriorSettle = new TransPriorSettle();
                log.error("userid: " + userId + " orgMerchantOrderId: " + orgMerchantOrderId);
                transPriorSettle.setMerchantOrderId(orgMerchantOrderId);
                List<TransPriorSettle> priorSettleList = transPriorSettleService.searchEntityList(transPriorSettle);
                log.error("priorSettleList.size()    " + priorSettleList.size());
                for(int i=0;i<priorSettleList.size();i++){
                    TransPriorSettle tps = priorSettleList.get(i);
                    String orderNum = tps.getOrderNum();
                    TransOrder transOrder = transOrderService.searchOrderByOrderNum(orderNum);
                    if(transOrder.getUserId().longValue() != userId.longValue()){
                        log.error("remove userid: " + userId);
                        priorSettleList.remove(i);
                    }
                }

                log.error("priorSettleList.size()    " + priorSettleList.size());
                if(priorSettleList.size() > 1){
                    String message = encryptAppMsg(0, "CX01", "撤销失败，存在重复订单号！");
                    sendAppMsg(message);
                    return null;
                }else if(priorSettleList.size() == 1){
                    transPriorSettle = priorSettleList.get(0);
                }else if(priorSettleList.size() < 1){
                    String message = encryptAppMsg(0, "CX01", "撤销失败，订单号不存在！");
                    sendAppMsg(message);
                    return null;
                }

//                TransPriorSettle transPriorSettle = transPriorSettleService.searchTransPriorSettle(terminalId, orgMerchantOrderId);
                Qian4SendLog orgSend = qian4SendLogService.getQian4SendLogByMOrderId(orgMerchantOrderId);
                TransOrder order = transOrderService.searchOrderByOrderNum(transPriorSettle.getOrderNum());
                if (Double.parseDouble(transAmt) / 100.0 != order.getTransMoney()) {
                    String message = encryptAppMsg(0, "CX01", "撤销失败，金额输入错误！");
                    sendAppMsg(message);
                    return null;
                }

                send = new Qian4SendLog();
                send.setCallType(0);
                send.setUserId(userId);
                send.setApplication("Void.Req");
                send.setOrderTypeId(REVOCATION);
                send.setSendTime(date);
                send.setSendSeqId(TimeUtils.getTimeToString());
//				send.setMerchantId(merchantId);//商户代码 ##
//				send.setTerminalId(terminalId);
                send.setPlatformId(platformId);//平台ID  ##
                send.setTransType("200000");//200000：撤销

                send.setMerchantOrderId(merchantOrderId);
                send.setMerchantOrderTime(DateConvertUtil.stringDate(merchantOrderTime, "yyyyMMddHHmmss"));
                send.setTransTime(send.getSendTime());
                send.setOrgTransId(orgSend.getBankOrderNum());
                send.setOrgTransTime(orgSend.getMerchantOrderTime());//原订单时间
                send.setOrgMerchantOrderId(orgMerchantOrderId);
                send.setTransAmt(transAmt);
                send.setMerchantSign(merchantSign);
                send.setSenderSign(senderSign);
                send.setServiceInfo(serviceInfo);
                send.setTerminalInfo(terminalInfo);
                //send.setMac(mac);
                send.setIp(URLDecoderTools.getRemoteHost(getRequest()));//IP

                send.setMerchantId(orgSend.getMerchantId());//商户号
                send.setTerminalId(orgSend.getTerminalId());//终端号

                send.setAccountNumber(orgSend.getAccountNumber());//卡号  安心一百 需要
                send.setTrack2Data(orgSend.getTrack2Data());
                send.setTrack3Data(null == orgSend.getTrack3Data() ? "" : orgSend.getTrack3Data());
                send.setPin(orgSend.getPin());

                //8583 需要传入
                send.setBankRef(transPriorSettle.getBankRef());
                send.setCollectionType(transPriorSettle.getCollectionType());
                send.setBankOrderNum(transPriorSettle.getBankOrderNum());
                send.setBatchId(transPriorSettle.getBatchId());
                send.setAuthorizationCode(transPriorSettle.getAuthorizationCode());

                //IC 卡
                send.setIcCardYu(orgSend.getIcCardYu());

                //添加 日志
				/*long sendId = qian4SendLogService.insertEntity(send);
				send.setId(sendId);*/
                Map<String, Object> result = new HashMap<String, Object>();
                Map<String, Object> resultMap = accountManageQ4Service.isCanRevocationOrder(send);
                int flag = (Integer) resultMap.get("status");
                if (flag == 1) {
                    if (null == transPriorSettle.getStatus() || 1 != transPriorSettle.getStatus().intValue()) {//如果不是 成功的订单  那么就不支持撤销
                        return null;//不返回数据   让客户端继续撤销
                    }

                    //添加 日志   在调用上海接口时  保证有一条撤销记录  所以在action中添加日志
                    long sendId = qian4SendLogService.insertEntity(send);
                    send.setId(sendId);


                    TransOrder transOrder = new TransOrder();
                    transOrder.setOrderNum(transPriorSettle.getOrderNum());
                    transOrder = transOrderService.searchEntity(transOrder);
                    //查询订单 修改金额
                    if (transOrder.getStatus().intValue() == 1) {//只用收款成功的才 减钱
                        accountManageQ4Service.updateUserMoney(transOrder, 0, transOrder.getChargeAmount());
                    }
                    //修改订单状态 为已撤销 作为一个事务提交  暂时用同步的方式   在isCanRevocationOrder 方法中实现
                    transOrderService.updateStatusClearing(transPriorSettle.getOrderNum(), 7, null);//发起撤销

//                    resultMap = accountManageQ4Service.revocationOrder(send);
                    resultMap = accountManageQ4Service.revocationOrderForZY(send);

                    result.put("reqCode", resultMap.get("reqCode"));
                    result.put("reqMsg", resultMap.get("reqMsg"));
                } else {
                    result.put("reqCode", resultMap.get("reqCode"));
                    result.put("reqMsg", resultMap.get("reqMsg"));
                }
                sendAppMsg(result);
            } else {
                log.warn("撤销我要收款时, 用户Id=" + userId + " 对应的用户不存在!");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (ConnectException e) {//请求 超时
            Map<String, Object> resultMap = revocationOrderTimeOut(send);
            int status = (Integer) resultMap.get("status");
            if (status == 0) {
                //保存 超时的撤销任务 ####################
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }

    /**
     * 撤销超时
     *
     * @return
     * @throws Exception
     */
    public Map<String, Object> revocationOrderTimeOut(Qian4SendLog send) throws Exception {
        Map<String, Object> resultMap = accountManageQ4Service.isCanRevocationOrder(send);
        int status = (Integer) resultMap.get("status");
        if (status == 1) {
            Date date = new Date();
            send.setMerchantOrderId(DateConvertUtil.dateString(date, "yyyyMMddHHmmssSSS"));
            send.setMerchantOrderTime(date);
            //添加 日志   在调用上海接口时  保证有一条撤销记录
            long sendId = qian4SendLogService.insertEntity(send);
            send.setId(sendId);
            resultMap = accountManageQ4Service.revocationOrder(send);
            int flag = (Integer) resultMap.get("status");
            if (flag == 0 && (send.timeOut == 1 || send.timeOut == 2 || send.timeOut == 3)) {
                resultMap = revocationOrderTimeOut(send);
            }
        }
        return resultMap;
    }
}
